package itsmap.systematic.exam;

import java.util.ArrayList;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class PatientListActivity extends Activity {

	private final int addPatient = 2;
	private final int getPatientList = 3;
	private final int getPatientInformation = 5;
	private final int editPatient = 6;
	private final int removePatient = 4;
	private ArrayList<PatientClass> mPatients;

	private ListView mpatientListView, mPatientInfolistView;

	private String color;
	private AlertDialog aDialog, mDialogEdit, mDialogDelete;
	private AlertDialog.Builder mBuilder, mBuilderEdit,mBuilderDelete;
	private PatientslistAdapter pla1;
	private PatientslistToResultsAdapter pla2;

	private static boolean first = true;

	private Context mContext;

	private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
		@Override
		public void onReceive(Context context, Intent intent) {
			// Get extra data included in the Intent

			String message = intent.getStringExtra("message");
			Log.d("receiver", "Got message: " + message);
			// startActivity(new Intent().setClass(context,
			// PatientListActivity.class));

			String action = intent.getAction();

			if (action.equals("favs")) {
				intent.setClass(context, PatientListActivity.class);
				try {
					setContentOfPatientList(intent);
					pla1 = new PatientslistAdapter(context,
							R.layout.patientlist_rowdataleft, mPatients);
					pla2 = new PatientslistToResultsAdapter(context,
							R.layout.patient_rowdatarigth, mPatients);
					mpatientListView.setAdapter(pla1);
					mPatientInfolistView.setAdapter(pla2);
				} catch (JSONException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}

			}

			if (action.equals("AddFavorite")) {
				Intent i = new Intent(context, Restapi.class);

				i.putExtra("action", getPatientList);
				// startActivityForResult(i, getPatientList);
				startService(i);
			}

			if (action.equals("getPatientInfo")) {
				String pInfo = message;
				intent = new Intent(context, PatientInformationActivity.class);
				intent.putExtra("jsonData", pInfo);

				startActivity(intent);
			}

			if (action.equals("checkNews")) {
				if (message.equals("2")) { // No news, check again
					Intent startNotice = new Intent(context, Restapi.class);
					startNotice.putExtra("action", 90);
					startService(startNotice);
				} else { // there are news

				}
			}
			if (action.equals("UpdateFavorite")) {
				Intent i = new Intent(context, Restapi.class);

				i.putExtra("action", getPatientList);
				startService(i);
			}
			if(action.equals("rmFav")){
				Intent i = new Intent(context, Restapi.class);

				i.putExtra("action", getPatientList);
				startService(i);
			}

		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.patient_listview_version2);

		mContext = this;
		if (this.first) {
			mPatients = new ArrayList<PatientClass>();

			mPatientInfolistView = (ListView) findViewById(R.id.list2);
			mpatientListView = (ListView) findViewById(R.id.list1);

			mPatientInfolistView
					.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {

						@Override
						public void onItemClick(AdapterView<?> arg0, View arg1,
								int arg2, long arg3) {
							// TODO Auto-generated method stub

						}

					});
			mpatientListView
					.setOnItemLongClickListener(new OnItemLongClickListener() {
						@Override
						public boolean onItemLongClick(AdapterView<?> parent,
								View view, int position, long arg3) {

							// setup Inflater
							LayoutInflater inflater = LayoutInflater
									.from(mContext);
							final View mView = inflater.inflate(
									R.layout.delete_patient_from_favc_dialog,
									null);
							// patient
							final PatientClass pc = mPatients.get(position);

							// builder setup
							mBuilderDelete = new AlertDialog.Builder(mContext);
							mBuilderDelete.setView(mView);

							final TextView nameTv = (TextView) mView
									.findViewById(R.id.deletePatientNameTextViewHeaderId);
							nameTv.setText(pc.getName());

							final TextView cprTv = (TextView) mView
									.findViewById(R.id.deletePatientCprTextViewHeaderId);
							cprTv.setText(pc.getCpr().subSequence(0, 6) + "-"
									+ pc.getCpr().substring(6, 10));

							mBuilderDelete.setPositiveButton(R.string.okBtn,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {

											Intent intent = new Intent(
													PatientListActivity.this,
													Restapi.class);
											intent.putExtra("action",
													removePatient);
											intent.putExtra("cpr", pc.getCpr());
											startService(intent);
										}
									}).setNegativeButton(R.string.cancelBtn,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();

										}
									});
							
							mDialogDelete = mBuilderDelete.create();
							mDialogDelete.show();

							return false;

						}
					});
			mpatientListView
					.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
						@Override
						public void onItemClick(AdapterView<?> parent,
								View view, int position, long id) {

							// setup Inflater
							LayoutInflater inflater = LayoutInflater
									.from(mContext);
							final View mView = inflater.inflate(
									R.layout.edit_patient_dialogview, null);
							// patient
							final PatientClass pc = mPatients.get(position);

							// Spinner setup
							Spinner spinner = (Spinner) mView
									.findViewById(R.id.EditPatientColorPickId);
							// Creating Adapter
							ArrayAdapter<CharSequence> adapter = ArrayAdapter
									.createFromResource(
											mContext,
											R.array.color_array,
											android.R.layout.simple_spinner_item);

							adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
							spinner.setAdapter(adapter);

							int i = adapter.getPosition(pc.getColor("fisk"));

							spinner.setSelection(i);
							spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

							// builder setup
							mBuilderEdit = new AlertDialog.Builder(mContext);
							mBuilderEdit.setView(mView);

							final String cpr = pc.getCpr();
							String note = pc.getNote();

							TextView cprTv = (TextView) mView
									.findViewById(R.id.editPatientToFavcCprTextView);
							cprTv.setText(cpr.substring(0, 6) + "-"
									+ cpr.substring(6, 10));

							final EditText noteEv = (EditText) mView
									.findViewById(R.id.editPatientToFavcNoteEditText);

							noteEv.setText(pc.getNote());

							// Setup btn for Dialog
							mBuilderEdit.setPositiveButton(R.string.okBtn,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {

											Intent intent = new Intent(
													PatientListActivity.this,
													Restapi.class);
											intent.putExtra("action",
													editPatient);
											intent.putExtra("cpr", pc.getCpr());
											intent.putExtra("note", noteEv
													.getText().toString());
											intent.putExtra("color", color);
											startService(intent);
										}
									}).setNegativeButton(R.string.cancelBtn,
									new DialogInterface.OnClickListener() {
										@Override
										public void onClick(
												DialogInterface dialog,
												int which) {
											dialog.cancel();

										}
									});
							mDialogEdit = mBuilderEdit.create();
							mDialogEdit.show();

						}

					});

			// get list info
			this.first = true;
			LocalBroadcastManager.getInstance(this).registerReceiver(
					mMessageReceiver, new IntentFilter("favs"));

			LocalBroadcastManager.getInstance(this).registerReceiver(
					mMessageReceiver, new IntentFilter("getPatientInfo"));

			LocalBroadcastManager.getInstance(this).registerReceiver(
					mMessageReceiver, new IntentFilter("checkNews"));

			LocalBroadcastManager.getInstance(this).registerReceiver(
					mMessageReceiver, new IntentFilter("getNews"));

			LocalBroadcastManager.getInstance(this).registerReceiver(
					mMessageReceiver, new IntentFilter("AddFavorite"));

			LocalBroadcastManager.getInstance(this).registerReceiver(
					mMessageReceiver, new IntentFilter("UpdateFavorite"));
			LocalBroadcastManager.getInstance(this).registerReceiver(
					mMessageReceiver, new IntentFilter("rmFav"));

			// Service to get favc Patient List
			Intent intent = new Intent(this, Restapi.class);
			intent.putExtra("action", getPatientList);
			startService(intent);

			// Service to start notification thread
			Intent startNotice = new Intent(this, Restapi.class);
			startNotice.putExtra("action", 90);
			startService(startNotice);

		}
	}

	public void addNewPatientBtn(View view) {

		LayoutInflater inflater = LayoutInflater.from(this);
		final View mView = inflater
				.inflate(R.layout.add_new_patient_favc, null);

		// Spinner setup
		Spinner spinner = (Spinner) mView
				.findViewById(R.id.addNewPatientColorPickId);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter
				.createFromResource(this, R.array.color_array,
						android.R.layout.simple_spinner_item);

		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		spinner.setAdapter(adapter);
		spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());

		// builder setup
		mBuilder = new AlertDialog.Builder(this);
		mBuilder.setView(mView);
		aDialog = mBuilder.create();

		final EditText cprInput = (EditText) mView
				.findViewById(R.id.addNewPationToFavcCprEditView);
		final EditText noteInput = (EditText) mView
				.findViewById(R.id.addNewPationToFavcNoteEditView);

		// setup btn for Dialog
		mBuilder.setPositiveButton(R.string.okBtn,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						String cpr = cprInput.getText().toString();
						String note = noteInput.getText().toString();

						Intent intent = new Intent(PatientListActivity.this,
								Restapi.class);
						intent.putExtra("action", addPatient);
						intent.putExtra("cpr", cpr);
						intent.putExtra("note", note);
						intent.putExtra("color", color);
						startService(intent);
					}
				}).setNegativeButton(R.string.cancelBtn,
				new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						dialog.cancel();

					}
				});

		mBuilder.show();
	}

	// For Spinner
	public class MyOnItemSelectedListener implements OnItemSelectedListener {

		public void onItemSelected(AdapterView<?> parent, View view, int pos,
				long id) {
			color = parent.getItemAtPosition(pos).toString();
		}

		public void onNothingSelected(AdapterView parent) {
			// color = "WHITE";
		}
	}

	protected void onActivityResult(int requestCode, int resultCode,
			Intent intent) {
		if (resultCode == RESULT_OK && requestCode == addPatient) {
			intent.setClass(this, PatientListActivity.class);

			Intent i = new Intent(this, Restapi.class);

			i.putExtra("action", getPatientList);
			startActivityForResult(i, getPatientList);

		} else if (resultCode == RESULT_OK && requestCode == getPatientList) {
			intent.setClass(this, PatientListActivity.class);

			try {
				setContentOfPatientList(intent);
				pla1 = new PatientslistAdapter(this,
						R.layout.patientlist_rowdataleft, mPatients);
				mpatientListView.setAdapter(pla1);

			} catch (JSONException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}

		}
	}

	private void setContentOfPatientList(Intent intent) throws JSONException {
		String testOfInputFromHttpRequest = intent.getStringExtra("message");

		JSONArray patientArray = new JSONArray(testOfInputFromHttpRequest);

		mPatients = new ArrayList<PatientClass>();
		for (int i = 0; i < patientArray.length(); i++) {
			JSONObject json = patientArray.getJSONObject(i);

			// json.getString("note");
			// json.getString("notificationMode");

			mPatients.add(new PatientClass(json.getString("cpr"), json
					.getString("name"), json.getString("color"), json
					.getString("note")));
		}

	}

	private class PatientslistAdapter extends ArrayAdapter<PatientClass> {
		private ArrayList<PatientClass> mItems;
		private Context mContext;

		public PatientslistAdapter(Context context, int textViewResourceId,
				ArrayList<PatientClass> items) {
			super(context, textViewResourceId, items);
			mItems = items;
			mContext = context;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.patientlist_rowdataleft, null);

			}
			PatientClass PC = mItems.get(position);
			if (PC != null) {
				TextView tt = (TextView) v.findViewById(R.id.patientCprText);
				if (tt != null) {
					String tempcpr = PC.getCpr().substring(0, 6) + "-"
							+ PC.getCpr().substring(6, 10);
					tt.setText(tempcpr);
					tt.setTextColor(PC.getColor());

				}
				TextView tv = (TextView) v.findViewById(R.id.patientNameText);
				if (tv != null) {
					tv.setText(PC.getName());
					tv.setTextColor(PC.getColor());
				}

			}

			return v;

		}

	}

	private class PatientslistToResultsAdapter extends
			ArrayAdapter<PatientClass> {
		private ArrayList<PatientClass> mItems;
		private Context mContext;

		public PatientslistToResultsAdapter(Context context,
				int textViewResourceId, ArrayList<PatientClass> items) {
			super(context, textViewResourceId, items);
			mItems = items;
			mContext = context;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			View v = convertView;
			if (v == null) {
				LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
				v = vi.inflate(R.layout.patient_rowdatarigth, null);
			}
			final PatientClass PC = mItems.get(position);
			if (PC != null) {
				Button btn = (Button) v.findViewById(R.id.seeTestResults);
				if (btn != null) {
					btn.setOnClickListener(new OnClickListener() {
						@Override
						public void onClick(View v) {

							// Toast
							int duration = Toast.LENGTH_LONG;
							Toast toast = Toast.makeText(mContext, "Loading: "
									+ PC.getCpr(), duration);
							toast.show();

							// Intent
							Intent intent = new Intent(
									PatientListActivity.this, Restapi.class);
							intent.putExtra("cpr", PC.getCpr());
							intent.putExtra("action", getPatientInformation);

							startService(intent);
						}
					});
				}
				Spinner spinner = (Spinner) v.findViewById(R.id.spinner1);
				if (spinner != null) {
					ArrayAdapter<CharSequence> adapter = ArrayAdapter
							.createFromResource(PatientListActivity.this,
									R.array.state_array,
									android.R.layout.simple_spinner_item);
					adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
					spinner.setAdapter(adapter);
					spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> arg0,
								View arg1, int arg2, long arg3) {
							PC.setState(arg0.getItemAtPosition(arg2).toString());

						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
							// TODO Auto-generated method stub

						}

					});

				}
			}

			return v;

		}
	}
}
